package lfm.mpr;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.Properties;
import db.AdminBaseDatosHelper;
import AsyncTask.TaskProgressBar_Validate_Download_Datos;
import Toast.PropertiesLFM;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class StartActivity extends Activity {
	
	private AdminBaseDatosHelper miBBDDHelper;
	private SharedPreferences prefs;
	private String user;
	private Properties properties;
	private TextView textview_version;
	
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.start);
	        
	        properties = PropertiesLFM.load_properties(StartActivity.this);
	        
	        textview_version = (TextView) findViewById(R.id.textView_version);
	        textview_version.setText(properties.getProperty("version"));
	        
	        miBBDDHelper = new AdminBaseDatosHelper(StartActivity.this);
	        //Miramos las preferencias de usuario si existen
	        prefs = getSharedPreferences("MisPreferencias", Context.MODE_PRIVATE);
	        user = prefs.getString("user", "");
	        
	        if(!PropertiesLFM.checkFolderApp(properties.getProperty("path"))) create_copy_directory_Assets_to_SD();
	        Inicializar_BD();
	        
	 }//end_onCreate
	 
	 
	 private void Inicializar_BD() {
			
	      try {
	    	  
	    	 AdminBaseDatosHelper miBBDDHelper = new AdminBaseDatosHelper(StartActivity.this);
	    	
	    	 if(properties.getProperty("schema").equals("create")) miBBDDHelper.CopyDataBase();
	    	 else miBBDDHelper.crearDataBase();
	    	 
			 new TaskProgressBar_Validate_Download_Datos(StartActivity.this, prefs, user).execute();	
		} 
	      catch(SocketTimeoutException e){
	    	  Toast.makeText(StartActivity.this, "No es posible conectar con el servidor, intentelo mas tarde", Toast.LENGTH_SHORT).show();
	    	  Log.i("LFM_Log","Tiempo de espera agotado, no se puede conectar con el servidor");
	      }
	      
	      catch (Exception e) {
			Log.i("LFM_Log","Error al inicializar la BD " + e.getMessage());
			e.printStackTrace();
		}
		
	}//end_Inicializar_BD()
	 
	 
	 private void create_copy_directory_Assets_to_SD() {
			
		    Log.i("LFM_Log","Copiando la carpeta assets en" + properties.getProperty("basepath") + "/doc/");
			String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		    String basepath = extStorageDirectory + properties.getProperty("basepath");

			// TODO Auto-generated method stub
			File folder_lfm = new File(Environment.getExternalStorageDirectory() + properties.getProperty("basepath"));
	        if(!folder_lfm.exists()) {
	            folder_lfm.mkdir();
	        }//end_if  
	        
	        File folder_lfm_doc = new File(Environment.getExternalStorageDirectory() + properties.getProperty("basepath") + "/doc");
	        if(!folder_lfm_doc.exists()) {
	        	folder_lfm_doc.mkdir();
	        }//end_if
	        
	        AssetManager assetManager = getResources().getAssets();
	        String[] files = null;
	        try {
	            files = assetManager.list("doc");
	        }//end_try
	        catch (Exception e) {
	            Log.e("read clipart ERROR", e.toString());
	            e.printStackTrace();
	        }//end_catch
	        
	        for(int i=0; i<files.length; i++) {
	            InputStream in = null;
	            OutputStream out = null;
	            try {
	              
	              in = assetManager.open("doc/" + files[i]);
	              out = new FileOutputStream(basepath + "/doc/" + files[i]);
	              copyFile(in, out);
	              in.close();
	              in = null;
	              out.flush();
	              out.close();
	              out = null;
	            } catch(Exception e) {
	                Log.e("copy clipart ERROR", e.toString());
	                e.printStackTrace();
	            }       
	        }
		}//end_copy_directory_Assets_to_SD
		
		private void copyFile(InputStream in, OutputStream out) throws IOException {
	        byte[] buffer = new byte[1024];
	        int read;
	        while((read = in.read(buffer)) != -1){
	          out.write(buffer, 0, read);
	        }
	    }//end_copyFile
		
}//end_StartActivity
